﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.IO;

using Microsoft.Win32;

namespace MuzičkiFeršterker
{
    /// <summary>
    /// Interaction logic for Window1.xaml
    /// </summary>
    public partial class Window1 : Window
    {
        private ContextMenu TabsContextMenu = new ContextMenu();
        protected ListView CurrListview;
        protected TabItem currTab;
        private TransVar T = new TransVar(); 
        PlayHandler ph;
        private List<PlayList> Playlists = new List<PlayList>();

        MenuItem MIclose; //menu item za zapiranje zavihka
        MenuItem MInew; //menu item za nov zavihek
        MenuItem MIrename; //menu item za preimenovanje zavihka
        MenuItem MISetting;//menu item za nastavitve
        MenuItem MIsaveToXSPF;
        MenuItem MIsaveToM3U;
        
        #region Ne Drkaj
        public Window1()
        {
            InitializeComponent();
            AddContextMenu();
            
            
        }
        #endregion

        #region Init metoda
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            try
            {
                ph = new PlayHandler();
                ph.SetElapsedLabel(textBlockElapsed);
                ph.SetRemainingLabel(textBlockRemaining);
                ph.SetTimeSlider(slider1);
                ph.SetTitleLabel(textBlockTitle);
                ph.SetMediaElement(mediaElement1);
                ph.onRequestNextSong += NextSong;
                AddNewTab();

                bindKeys();
                Settings.LoadSettings();
                T = new TransVar(Settings.Instance.getLanguagePath());
                //if (Settings.Instance.AllowedFileTypes == null)
                //    Settings.Default.AllowedFileTypes
                LoadTranslation();
                

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

        }
        #endregion

        #region Event metode
        private void button2_Click(object sender, RoutedEventArgs e) // ADD FILES
        {
            try
            {
                OpenFileDialog open = new OpenFileDialog();
                open.Multiselect = true;
                open.Filter = "Audio files (*.mp3, *.wma, *.wav)|*.mp3;*.wma;*.wav|MP3 Files (*.mp3)|*.mp3|Windows Media Audio files (*.wma)|*.wma|Waveform Audio File (*.wav)|*.wav";
                if (open.ShowDialog() == true) //če je dialog OK
                {
                    currTab = tabControl1.SelectedItem as TabItem;

                    if (currTab == null)
                        throw new Exception("NULL current tab!");
                    else
                    {
                        CurrListview = currTab.Content as ListView;
                        if (CurrListview == null)
                            throw new Exception("NULL Current List View!");
                    }
                    //MessageBox.Show("OK");
                    String[] files = open.FileNames; //dobimo vse datoteke, ki smo jih izbrali
                    for (int i = 0; i < files.Length; i++)
                    {
                        //tabControl1.SelectedContent;
                        //tabItem1.cont
                        Playlists[tabControl1.SelectedIndex].Add(files[i]);
                        //CurrListview.Items.Add(Playlists[tabControl1.SelectedIndex].GetLastSong().Name);
                    }

                }
                else
                //MessageBox.Show("Canceled!");
                { }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            
        }

        public class CloseableTabItem : TabItem
        {
            static CloseableTabItem()
            {
                DefaultStyleKeyProperty.OverrideMetadata(typeof(CloseableTabItem),
                new FrameworkPropertyMetadata(typeof(CloseableTabItem)));
            }
        }

        private void Removebutton_Click(object sender, RoutedEventArgs e) //zbrišemo izbrane elemente s playlista
        {
            try
            {
                currTab = tabControl1.SelectedItem as TabItem;
                if (currTab == null)
                    throw new Exception("NULL current tab!");
                else
                {
                    CurrListview = currTab.Content as ListView;
                    if (CurrListview == null)
                        throw new Exception("NULL Current List View!");
                }
                while (CurrListview.SelectedItems.Count > 0)
                {
                    CurrListview.Items.Remove(CurrListview.SelectedItem);
                    Playlists[tabControl1.SelectedIndex].Remove(CurrListview.SelectedIndex);
                }
                CurrListview.Items.Refresh();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void tabControl1_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            
        }

        private void PlayButton_Click(object sender, RoutedEventArgs e)
        {
            //PLAY Button
            ph.PlayPause();
        }

        private void StopButton_Click(object sender, RoutedEventArgs e)
        {
            //STOP Button
            ph.Stop();
        }

        private void Pausebutton_Click(object sender, RoutedEventArgs e)
        {
            ph.Pause();
        }

        private void Nextbutton_Click(object sender, RoutedEventArgs e)
        {
            NextSong();
        }

        public void NextSong()
        {
            int selectedIndex = 0;
                tabControl1.Dispatcher.Invoke((Action)delegate
                {
                    selectedIndex = tabControl1.SelectedIndex;
                    Song temp = Playlists[selectedIndex].GetNextSong();
                    if (temp != null)
                        Dispatcher.Invoke((Action)delegate
                        {
                            ph.SetSong(temp);
                            ph.Play();
                            //play.PlaySong(temp);
                        });
                });
        }

        private void Backbutton_Click(object sender, RoutedEventArgs e)
        {
            Song temp = Playlists[tabControl1.SelectedIndex].GetPrevSong();
            if (temp != null)
            {
                ph.SetSong(temp);
                ph.Play();
            }
        }

        private void Clearbutton_Click(object sender, RoutedEventArgs e)
        {
            //CLEAR button

            currTab = tabControl1.SelectedItem as TabItem;
            CurrListview = currTab.Content as ListView;
            CurrListview.Items.Clear();
            Playlists[tabControl1.SelectedIndex].ClearPlaylist();
            //XmlSerializator.Save(@".\TransVar.xml", T);
            
            

        }

        private void NewTabbutton_Click(object sender, RoutedEventArgs e)
        {
            AddNewTab();
        }

        #region Drag & Drop
        private void listView_DragEnter(object sender, DragEventArgs e)
        {
            bool goForIt = false;
            if (e.Data.GetDataPresent(DataFormats.FileDrop, true))
            {
                goForIt=false;
                string[] filenames = e.Data.GetData(DataFormats.FileDrop, true) as string[];
                foreach (string filen in filenames)
                {
                    if (System.IO.Path.GetExtension(filen).ToLowerInvariant() == ".xml")
                    {
                        goForIt = true;
                        break;
                    }

                    foreach(string ext in Settings.Default.AllowedFileTypes)
                    {
                        if (System.IO.Path.GetExtension(filen).ToLowerInvariant() == ext.Substring(1, ext.Length - 1))
                        {
                            goForIt = true;
                            break;
                        }
                     }
                }

            }
            if (goForIt)
            {
                e.Effects = DragDropEffects.Move;
                e.Handled = true;
            }
            
        }
        private void listView_Drop(object sender, DragEventArgs e)
        {
            // Dodamo glasbo z drag&drop
            bool goForIt = false;
            string[] filenames = e.Data.GetData(DataFormats.FileDrop, true) as string[];
            foreach (string filen in filenames)
            {
                if (System.IO.Path.GetExtension(filen).ToLowerInvariant() == ".xml")
                {
                    Playlists[tabControl1.SelectedIndex].ImportFromXSPF(filen);
                    break;
                }

                if (System.IO.Path.GetExtension(filen).ToLowerInvariant() == ".m3u")
                {
                    Playlists[tabControl1.SelectedIndex].ImportFromM3U(filen);
                    break;
                }

                foreach (string ext in Settings.Default.AllowedFileTypes)
                {
                    
                    if (System.IO.Path.GetExtension(filen).ToLowerInvariant() == ext.Substring(1,ext.Length-1))
                    {
                        goForIt = true;
                        break;
                    }
                }
            }
            if (goForIt)
            {
                for (int i = 0; i < filenames.Length; i++)
                {
                    Playlists[tabControl1.SelectedIndex].Add(filenames[i]);
                }
            }


        }
        #endregion
        private void listView1_PreviewMouseDoubleClick(object sender, MouseButtonEventArgs e)
        {   // Double click na listView za recimo play
            if (((ListView)sender).SelectedItems.Count == 1)
            {
                ph.SetSong(Playlists[tabControl1.SelectedIndex].GetSong(((ListView)sender).SelectedIndex));
                ph.Play();
                //play.PlaySong(Playlists[tabControl1.SelectedIndex].GetSong(((ListView)sender).SelectedIndex));
                Playlists[tabControl1.SelectedIndex].PlayingSongIndex = ((ListView)sender).SelectedIndex;
                e.Handled = true;
            }
        }

        // song position
        private void slider1_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
        {
            if (ph != null)
            {
                int a = (int)slider1.Value;
                //play.SetSongPosition(a);
            }
        }

        //volume
        private void slider2_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
        {
            if (ph != null)
            {
                //float a = (float)slider2.Value;
                ph.Volume = (int)slider2.Value;
                slider2.ToolTip = Convert.ToInt32(slider2.Value).ToString();
            }
        }
        #endregion

        #region Translations
        private void LoadTranslation()
        {
            buttonNext.ToolTip = T.tNEXT;
            buttonPause.ToolTip = T.tPAUSE;
            buttonPlay.ToolTip = T.tPLAY;
            buttonPrevious.ToolTip = T.tPREV;
            buttonStop.ToolTip = T.tSTOP;

            buttonClearList.ToolTip = T.tCLRLIST;
            buttonAddSong.ToolTip = T.tADDSONG;
            buttonRemoveSong.ToolTip = T.tREMSONG;

            button9.ToolTip = T.tNEWTAB;

            textBlockElapsed.ToolTip = T.tPLAYEDTOOLTIP;
            textBlockRemaining.ToolTip = T.tREMAININGTOOLTIP;

            labelBalance.Content = T.tBALANCE;
            labelVolume.Content = T.tVOLUME;
            buttonShuffle.ToolTip = T.tSHUFFLEOFFTOOLTIP;
            MInew.Header = T.tNEWTABmenu;
            MInew.ToolTip = T.tNEWTAB;
            MIclose.Header = T.tCLOSETABmenu;
            MIclose.ToolTip = T.tREMTAB;
            MIrename.Header = T.tRENAMETABmenu;
            MIrename.ToolTip = T.tRENAMETAB;
            MISetting.Header = T.tSETTINGS;
            MIsaveToXSPF.Header = "Save to XSPF";
            MIsaveToM3U.Header = "Save to M3U";
        }
        #endregion

        #region Menus and stuff
        private void AddContextMenu()
        {
            MInew = new MenuItem();
            MInew.Click += new System.Windows.RoutedEventHandler(this.AddNewTab);

            MIclose = new MenuItem();
            MIclose.Click+=new RoutedEventHandler(this.CloseTab);

            MIrename = new MenuItem();
            MIrename.Click += new RoutedEventHandler(this.RenameTab);

            MIsaveToXSPF = new MenuItem();
            MIsaveToXSPF.Click += new RoutedEventHandler(SaveToXSPF);

            MIsaveToM3U = new MenuItem();
            MIsaveToM3U.Click += new RoutedEventHandler(SaveToM3U);

            TabsContextMenu.Items.Add(MInew);
            TabsContextMenu.Items.Add(MIclose);
            TabsContextMenu.Items.Add(MIrename);
            TabsContextMenu.Items.Add(MIsaveToXSPF);
            TabsContextMenu.Items.Add(MIsaveToM3U);

            MISetting = new MenuItem();
            
            MISetting.Click += new RoutedEventHandler(this.SettingsShow);
            this.ContextMenu = new ContextMenu();
            this.ContextMenu.Items.Add(MISetting);

        }

        #endregion

        #region Tabs
        private void AddNewTab()
        {
            TabItem temp = new TabItem();
            temp.Header = T.tNEWTABheader + tabControl1.Items.Count.ToString();
            temp.Name = "NewTab" + tabControl1.Items.Count.ToString();
            //temp.MouseDoubleClick += RenameTab;
            temp.ContextMenu = TabsContextMenu;
            ListView list = new ListView();
            list.MouseDoubleClick += listView1_PreviewMouseDoubleClick;
            list.AllowDrop = true;
            list.Drop += new DragEventHandler(listView_Drop);
            list.DragEnter+=new DragEventHandler(listView_DragEnter);
            

            temp.Content = list;
            
            int i = tabControl1.Items.Add(temp);
            tabControl1.SelectedIndex = i;

            Playlists.Add(new PlayList(list));
        }

        private void AddNewTab(object sender, EventArgs e)
        {
            AddNewTab();
        }

        private void CloseTab(object sender, RoutedEventArgs e)
        {
             Playlists.RemoveAt(tabControl1.SelectedIndex);
             tabControl1.Items.Remove(tabControl1.SelectedItem);             

        }
        private void RenameTab(object sender, RoutedEventArgs e)
        {
            if(e.Source!=(CurrListview))
            currTab = tabControl1.SelectedItem as TabItem;
            Form1 GetHead = new Form1(currTab.Header.ToString(), T.tINSERTNEWSTRING);
            GetHead.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent;
            GetHead.ShowDialog();
            if (GetHead.DialogResult == System.Windows.Forms.DialogResult.OK)
                currTab.Header = GetHead.HEADER;
            e.Handled = true;
        }
        

        private void SaveToXSPF(object sender, RoutedEventArgs e)
        {
            System.Windows.Forms.SaveFileDialog b = new System.Windows.Forms.SaveFileDialog();
            b.DefaultExt = "xml";
            b.Filter = "XML playlist files (*.xml)|*.xml";
            if (b.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                Playlists[tabControl1.SelectedIndex].ExportToXSPF(b.FileName);
            }
        }

        private void SaveToM3U(object sender, RoutedEventArgs e)
        {
            System.Windows.Forms.SaveFileDialog b = new System.Windows.Forms.SaveFileDialog();
            b.DefaultExt = "m3u";
            b.Filter = "M3U playlist files (*.m3u)|*.m3u";
            if (b.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                Playlists[tabControl1.SelectedIndex].ExportToM3U(b.FileName);
            }
        }
        #endregion

        #region Balance slider
        private void slider3_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
        {
            if (ph != null)
            {
                ph.Balance = (int)slider3.Value;
                slider3.ToolTip = Convert.ToInt32(slider3.Value).ToString();
            }
        }

        private void slider3_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            slider3.Value = 0;
        }
        #endregion

        private void button1_Click(object sender, RoutedEventArgs e) //shuffling button click
        {
            Playlists[tabControl1.SelectedIndex].Shuffling = !Playlists[tabControl1.SelectedIndex].Shuffling;
            BitmapImage bi;
            if (Playlists[tabControl1.SelectedIndex].Shuffling == false)
            {
                bi = new BitmapImage(new Uri("pack://application:,,/Icons/button-shuffle_green.png"));
                buttonShuffle.ToolTip = T.tSHUFFLEOFFTOOLTIP;

            }
            else
            {
                bi = new BitmapImage(new Uri("pack://application:,,/Icons/button-shuffle_red.png"));
                buttonShuffle.ToolTip = T.tSHUFFLEONTOOLTIP;
            }
            ShuffleButtonIcon.Source = bi;
            
        }

        private void SettingsShow(object sender, RoutedEventArgs e)
        {
            SettingsShow();
        }
        private void SettingsShow()
        {
            SettingsWindow settingsW = new SettingsWindow("Header", T);            
            if (settingsW.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                Color barva = Color.FromArgb(settingsW.WindowBgColor.A, settingsW.WindowBgColor.R, settingsW.WindowBgColor.G, settingsW.WindowBgColor.B);
                if (settingsW.gradient == true)
                {
                    Color barva2 = Color.FromArgb(settingsW.WindowBgColor2.A, settingsW.WindowBgColor2.R, settingsW.WindowBgColor2.G, settingsW.WindowBgColor2.B);
                    this.Background = new LinearGradientBrush(barva, barva2, 1);
                }
                else
                {
                    this.Background = new SolidColorBrush(barva);
                }
                Color TabBarva = Color.FromArgb(settingsW.TabBgColor.A, settingsW.TabBgColor.R, settingsW.TabBgColor.G, settingsW.TabBgColor.B);
                foreach (TabItem t in tabControl1.Items)
                {
                    ListView li = t.Content as ListView;
                    li.Background = new SolidColorBrush(TabBarva);
                }
                if (settingsW.langChg == true)
                {
                    T = settingsW.tv;
                    LoadTranslation();
                }
            }

        }

        private void buttonAddFolder_Click(object sender, RoutedEventArgs e)
        {
            System.Windows.Forms.FolderBrowserDialog folder = new System.Windows.Forms.FolderBrowserDialog();
            if (folder.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                Playlists[tabControl1.SelectedIndex].AddFolder(folder.SelectedPath);
            }
        }

        #region Commands and Key bindings
        public static RoutedCommand addQueue = new RoutedCommand();
        private void bindKeys()
        {
            CommandBinding cb = new CommandBinding(addQueue, addQueueExecute);
            this.CommandBindings.Add(cb);
            KeyGesture cg = new KeyGesture(Key.Q, ModifierKeys.Alt);
            InputBinding ib = new InputBinding(addQueue, cg);
            this.InputBindings.Add(ib);
        }

        private void addQueueExecute(object sender, ExecutedRoutedEventArgs e)
        {
            int i = Playlists[tabControl1.SelectedIndex].ListView.SelectedIndex;
            Playlists[tabControl1.SelectedIndex].AutoQueueUnqueue();
            Playlists[tabControl1.SelectedIndex].ListView.SelectedIndex = i;
        }
        #endregion

        private void button1_Click_1(object sender, RoutedEventArgs e)
        {
            T = new TransVar(@".\TransVarSLO.xml");
            LoadTranslation();
            InvalidateVisual();
            
        }

        private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            Settings.SaveSettings();
        }
    }
}
